package main

import (
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"log"
)

// 全局的数据库操作，不同的方法都可以访问到这个变量
var db *gorm.DB
var err error

func main() {
	dsn := "51201300094:51201300094@Fangli@tcp(172.20.3.251:3306)/51201300094?charset=utf8&parseTime=True&loc=Local"
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})
	if err != nil {
		// https://zhuanlan.zhihu.com/p/105759117
		log.Fatal("db connect error")
	}

	//defer db.Close()    //延时调用函数
	db.AutoMigrate(&StudentInfo{})

	r := gin.Default()
	apiGroup := r.Group("api")
	v1Group := apiGroup.Group("v1")
	v1Group.GET("/student", getStudentInfo)       //获取学生信息
	v1Group.GET("/students", getAllStudentInfo)   //获取所有学生信息
	v1Group.POST("/student", saveStudentInfo)     //保存学生信息
	v1Group.PUT("/student", updateStudentInfo)    //修改学生信息
	v1Group.DELETE("/student", deleteStudentInfo) //删除学生信息

	_ = r.Run(":8080")
}

//获取所有学生信息
func getAllStudentInfo(c *gin.Context) {
	var studentInfos []StudentInfo
	result := db.Find(&studentInfos)
	if result.Error != nil {
		c.JSON(500, gin.H{"message": "查询为空"})
		c.Abort()
	} else {
		c.JSON(200, gin.H{"message": "成功", "data": studentInfos})
	}
}

//获取学生信息
func getStudentInfo(c *gin.Context) {
	xh := c.Query("xh")
	var studentInfo StudentInfo
	result := db.First(&studentInfo, "xh=?", xh)
	if result.Error != nil {
		c.JSON(500, gin.H{"message": "查询为空"})
		c.Abort()
	} else {
		c.JSON(200, gin.H{"message": "成功", "data": studentInfo})
	}
}

//保存学生信息
func saveStudentInfo(c *gin.Context) {
	json := StudentInfo{}
	c.BindJSON(&json)
	var studentInfo StudentInfo
	result := db.First(&studentInfo, json.Xh)
	if result.RowsAffected >= 1 {
		c.JSON(500, gin.H{"message": "学号已经存在"})
		c.Abort()
	} else {
		// Insert
		create := db.Create(&json)
		if create.RowsAffected == 1 {
			c.JSON(200, gin.H{"message": "保存成功", "data": nil})
			c.Abort()
		} else {
			c.JSON(500, gin.H{"message": "保存失败", "data": nil})
		}
	}
}

//修改学生信息
func updateStudentInfo(c *gin.Context) {
	json := StudentInfo{}
	c.BindJSON(&json)
	updates := db.Model(&json).Updates(json)

	if updates.RowsAffected == 1 {
		c.JSON(200, gin.H{"message": "修改成功", "data": nil})
		c.Abort()
	} else {
		c.JSON(500, gin.H{"message": "修改失败", "data": nil})
	}
}

//删除学生信息
func deleteStudentInfo(c *gin.Context) {
	json := StudentInfo{}
	c.BindJSON(&json)
	delete := db.Delete(&json)
	if delete.RowsAffected == 1 {
		c.JSON(200, gin.H{"message": "删除成功", "data": nil})
		c.Abort()
	} else {
		c.JSON(500, gin.H{"message": "删除失败", "data": nil})
	}
}
